package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Author: 李旭
 * @Time: 11:46
 * @Description:
 * 订单微服务
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;
    //查询结算页面
    @GetMapping("/trade")
    public Map<String,Object> trade(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        Map<String,Object> result = new HashMap<>();
        //1:用户收货地址
        List<UserAddress> userAddressList = userFeignClient.getUserInfoAddress();
        result.put("userAddressList",userAddressList);
        //2:商品清单
        List<CartInfo> cartInfoList = cartFeignClient.checkedCartInfoList();

        //订单详情集合
        List<OrderDetail> detailArrayList = cartInfoList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            //sku_id
            orderDetail.setSkuId(cartInfo.getSkuId());
            //图片
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            //名称
            orderDetail.setSkuName(cartInfo.getSkuName());
            //数量
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            //实时价格
            BigDecimal price = productFeignClient.getPrice(cartInfo.getSkuId());
            orderDetail.setOrderPrice(price);
            return orderDetail;
        }).collect(Collectors.toList());
        result.put("detailArrayList",detailArrayList);
        //3、交易号  防止幂等性问题
        //3.1:UUID  1)生成UUID  2：保存UUID到缓存中
        String tradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("tradeNo:" + userId ,tradeNo);
        result.put("tradeNo",tradeNo);
        //3.2: MD5(商品ID+用户Id+盐值） 计算
        //3.3: 时间戳 毫秒  2：保存缓存中

        //4:总件数  stream   List<OrderDetail>
        long totalNum = detailArrayList.stream().collect(
                Collectors.summarizingLong(OrderDetail::getSkuNum)).getSum();
        result.put("totalNum",totalNum);
        //5:总金额
        BigDecimal totalAmount = new BigDecimal(0);
        //detailArrayList.stream().collect(Collectors.)
        for (OrderDetail orderDetail : detailArrayList) {
            totalAmount = totalAmount.add(orderDetail.getOrderPrice()
                    .multiply(new BigDecimal(orderDetail.getSkuNum())));
        }
        result.put("totalAmount",totalAmount);
        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(String tradeNo, @RequestBody OrderInfo orderInfo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1:校验交易号  防止幂等性问题
        if(!StringUtils.isEmpty(tradeNo)){
            Object o = redisTemplate.opsForValue().get("tradeNo:" + userId);
            if(null != o){
                if(!o.equals(tradeNo)){
                    return Result.fail().message("不要重新提交订单");
                }
            }else{
                return Result.fail().message("不要重新提交订单");
            }
        }else{
            return Result.fail().message("非法操作");
        }
        //删除交易号
        redisTemplate.delete("tradeNo:" + userId);

        //2:校验库存  连接库存管理系统  仓库系统  进销存系统
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean flag = orderInfoService.hasStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
            if (!flag) {
                //无货
                return Result.fail().message(orderDetail.getSkuName() + "|已经卖完了");
            }
        }
        //3:保存订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrder(orderInfo);
        return Result.ok(orderId);
    }

    //根据订单ID查询订单对象
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return  orderInfoService.getOrderInfo(orderId);
    }
    //接收库存系统发起的 Http请求的 拆单请求
    @PostMapping("/orderSplit")
    public List<Map> orderSplit(Long orderId,String wareSkuMap){
        //wareSkuMap :  [{"wareId":"1","skuIds":["2","10"]},{"wareId":"2","skuIds":["3"]}]
        //说明： wareId:仓库的编号
        //       skuIds:在此仓库的商品ID
        //1:肯定需要拆单
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        //2：响应值 返回值
        return orderInfoList.stream().map (orderInfo ->
                orderInfoService.initWareOrder(orderInfo)).collect(Collectors.toList());
    }


}
